﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using KC.DataAccess.MV6;


public partial class _Default : System.Web.UI.Page
{
	public MV6DataContext dc = new MV6DataContext(ConfigurationManager.ConnectionStrings["MV6"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    { if (IsPostBack) return; }
    protected void rPosts_Load(object sender, EventArgs e)
    {
	    int Page = 0,
		   lastPage = (int)((double)dc.Posts.Count() / 10L),
		   ItemsPerPage = int.Parse(ConfigurationManager.AppSettings["ItemsPerPage"] ?? "10");
	    if (Request.QueryString["Page"] != null)
		    int.TryParse(Request.QueryString["Page"], out Page);

	    var posts = (from p in dc.Posts
				  where p.isEnabled == true
				  orderby p.Created descending
				  select p).Skip(Page * ItemsPerPage).Take(ItemsPerPage);
	    rPosts.DataSource = posts;
	    rPosts.DataBind();

	    hlNewer.Visible = Page > 0;
	    hlOlder.Visible = Page < lastPage;
	    
	    hlNewer.NavigateUrl = Page - 1 > 0
		    ?".?Page=" + (Page - 1).ToString()
		    : ".";
	    hlOlder.NavigateUrl = ".?Page=" + (Page + 1).ToString();
	    
    }
    protected void rPosts_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
		if (sender == null || e == null) return; // For some reason, repeaters databind inanimate objects such as headers and footers... OK, whatever.
		Post p = (Post)e.Item.DataItem;
	    HyperLink hl = (HyperLink)e.Item.FindControl("hlTitle");
	    hl.Text = p.Title;
	    hl.NavigateUrl = string.IsNullOrEmpty(p.FriendlyName)
		    ? "Post.aspx?ID=" + p.ID.ToString()
		    : "Post.aspx?Title=" + p.FriendlyName;
	    hl.ToolTip = "Navigate to Post " + p.ID.ToString();

	    Label lblBody = (Label)e.Item.FindControl("lblBody");
	    lblBody.Text = p.Body
		    .Replace("<br /><br />", "<br />")
		    .Replace("!notruncate", "")
		    .Trim();
    }
}